<template>
	<view class="ff-scroll-list">
		<template v-if="isFor">
			<view class="ff-scroll-list-item" v-for="(item, index) in list" :key="index">
				<slot name="default" :list="list" :item="item" :page="page" :size="size" :total="total">
					{{item}}
				</slot>
			</view>
		</template>
		<template v-else>
			<slot name="default" :list="list" :page="page" :size="size" :total="total">{{list}}</slot>
		</template>
	</view>
</template>

<script>
	export default {
		name: "ff-page-list",
		components: {},
		props: {
			size: {
				type: Number,
				default: 15
			},
			isFor: {
				type: Boolean,
				default: true
			},
		},
		created() {
			
		},
		data() {
			return {
				page: 0,
				total: null,
				list: [],
			};
		},
		computed: {
			pageRefresh(){
				return this.$parent.$attrs.pageRefresh;
			},
		},
		methods: {
			//获取列表
			loadList(type = 'refresh') {
				let page = null;
				let uuid = this.$ff.util.guid();
				if (type === 'add') {
					if (this.total != null) {
						if (this.list.length >= this.total) {
							page = this.page - 1;
							this.pageRefresh.pushLoadFinish();
							return;
						}
					}
					page = this.page + 1;
					this.pageRefresh.pushLoadLoading(uuid);
				}
				if (type === 'refresh') {
					page = 1;
					this.pageRefresh.pullRefreshLoading(uuid);
				}
				this.$emit('loadList', page, this.size, {
					complete: (list = [], total = 0) => {
						if (this.pageRefresh.uuid != uuid) {
							console.log("当前请求已经被丢弃");
							return;
						}
						if (type === 'add') {
							this.page = page;
							this.list = [...this.list, ...list];
							if (this.total == null) {
								this.total = total;
							}
							this.pageRefresh.pushLoadComplete();
						}
						if (type === 'refresh') {
							this.page = page;
							this.list = list;
							this.total = total;
							this.pageRefresh.pullRefreshComplete();
						}
					},
					error: (data = {}) => {
						if (this.pageRefresh.uuid != uuid) {
							console.log("add 当前请求已经被丢弃");
							return;
						}
						if (type === 'add') {
							this.pageRefresh.pushLoadError(data);
						}
						if (type === 'refresh') {
							this.pageRefresh.pullRefreshError(data);
						}
					}
				});
			},
			//下拉刷新事件
			pullRefreshLoadingChange(e) {
				this.loadList('refresh');
			},
			//上滑加载事件
			pushLoadLoadingChange(e) {
				this.loadList('add');
			}
		}
	}
</script>

<style>
	.ff-scroll-list {
		width: inherit;
		height: inherit;
		overflow: hidden;
	}
	.ff-page-refresh {
		width: 100%;
		height: 100%;
	}
</style>